<?php
declare (strict_types=1);

namespace app\admin\controller;

use app\BaseController;
use app\common\service\AdminUserService;
use think\facade\Validate;

//后台公共控制器
class Pub extends BaseController
{

    /*
     * @title 登录
     * */
    public function login()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param();
            $rule = [
                'phone' => 'require',
                'password' => 'require',
            ];
            $message = [
                'phone.require' => '登录名/手机号不能为空',
                'password.require' => '密码不能为空',
            ];
            //验证器验证
            $validate = Validate::rule($rule)->message($message);
            if (!$validate->check($param)) {
                return $this->error($validate->getError());
            }
            $AdminUserService = AdminUserService::ins();
            //检查登录信息是否正确
            $result = $AdminUserService->login($param['phone'], $param['password']);
            if (!$result) {
                return $this->error($AdminUserService->error);
            }
            //是否记住登录状态
            $remember = $this->request->param('remember', 0);
            //设置登录状态
            $AdminUserService->setLogin($result, (int)$remember);
            return $this->success("登录成功", ['url' => url('admin/index/index')->build()]);
        } else {
            $user_info = AdminUserService::ins()->checkLogin();
            if ($user_info) {
                return redirect('/admin/index/index');
            }
            return view();
        }
    }

    /*
     * @title 登出
     * */
    public function logout()
    {
        AdminUserService::ins()->clearLogin();
        return redirect('/admin/index/index');
    }

}